package com.game.service.socket;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.game.service.app.Utils.LogDate;
import static com.game.service.define.RoomConfig.LOG_NAME_ERROR;

public class FileUtils {
    static ExecutorService executor = Executors.newSingleThreadExecutor();

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String str, String filePath, String fileName) {
        executor.submit(() -> {
            //生成文件夹之后，再生成文件，不然会出错
            makeFilePath(filePath, fileName);

            String timeMillis = formatter.format(System.currentTimeMillis());

            String strFilePath = filePath + fileName;
            // 每次写入时，都换行写
            String strContent = timeMillis + "->" + str + "\r\n";
            try {
                File file = new File(strFilePath);
                if (!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                raf.seek(file.length());
                raf.write(strContent.getBytes(StandardCharsets.UTF_8));
                raf.close();
            } catch (Exception ignored) {
            }
        });

    }

    //生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            String error = "makeFilePath()" + e + "\n" + Arrays.toString(e.getStackTrace());
            FileUtils.writeTxtToFile(error, LogDate(), LOG_NAME_ERROR);
        }
        return file;
    }

    //生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
        }
    }

    //读取指定目录下的所有TXT文件的文件内容
    public static String getFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream in = new FileInputStream(file);
                    if (in != null) {
                        InputStreamReader inputReader = new InputStreamReader(in, StandardCharsets.UTF_8);
                        BufferedReader buff = new BufferedReader(inputReader);
                        String line;
                        //分行读取
                        while ((line = buff.readLine()) != null) {
                            content += line + "\n";
                        }
                        in.close();//关闭输入流
                    }
                } catch (Exception e) {
                }
            }
        }
        return content;
    }


    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    public static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    public static String getTime() {
        return formatter.format(System.currentTimeMillis()) + " ";
    }

}
